﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.SessionState;
using System.Web;
using A2DFramework.SessionService.Configuration;
using A2DFramework.SecurityService;

namespace A2DFramework.SessionService
{
    public class MongoDBSessionIDManager : SessionIDManager
    {
        private Random rnd = new Random();
        private object oLock = new object();

        public override string CreateSessionID(System.Web.HttpContext context)
        {
            int index = 0;
            lock(this.oLock)
            {
                index = rnd.Next(SessionConfiguration.SessionServerIdentities.Length);
            }
            string sessionId = string.Format("{0}.{1}", SessionConfiguration.SessionServerIdentities[index], base.CreateSessionID(context));
            return sessionId;
        }

        public override string Encode(string id)
        {
            return RawDESEncryptor.Encode(id, SessionConfiguration.DESKey);
        }
        public override string Decode(string id)
        {
            return RawDESEncryptor.Decode(id, SessionConfiguration.DESKey);
        }

        public override bool Validate(string id)
        {
            string prefix;
            string realId;

            if (!Helper.ParseSessionID(id, out prefix, out realId))
                return false;

            return base.Validate(realId);
        }
    }
}
